<template>
  <div class="purchase-return-order-audit">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="退货单号">
            <el-input v-model="searchForm.returnNo" placeholder="请输入退货单号" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="已提交" :value="1" />
              <el-option label="审核通过" :value="2" />
              <el-option label="审核驳回" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        border
      >
        <el-table-column prop="returnNo" label="退货单号" width="180" />
        <el-table-column prop="orderNo" label="采购订单号" width="180" />
        <el-table-column prop="creatorName" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="statusDesc" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.statusDesc }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalReturnAmount" label="退货总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalReturnAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看详情</el-button>
            <el-button 
              v-if="row.status === 1" 
              type="text" 
              type="primary" 
              @click="handleAudit(row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="退货单详情"
      width="800px"
    >
      <div v-if="detailData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退货单号">{{ detailData.returnNo }}</el-descriptions-item>
          <el-descriptions-item label="采购订单号">{{ detailData.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ detailData.creatorName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(detailData.status)">{{ detailData.statusDesc }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="退货总金额">¥{{ detailData.totalReturnAmount }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 退货商品列表 -->
        <div style="margin-top: 20px;">
          <h4>退货商品</h4>
          <el-table :data="detailData.items" border>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="returnQuantity" label="退货数量" width="100" />
            <el-table-column prop="returnPrice" label="退货单价" width="120" />
            <el-table-column prop="returnAmount" label="退货金额" width="120" />
            <el-table-column prop="reason" label="退货原因" />
          </el-table>
        </div>

        <!-- 审核信息 -->
        <div v-if="detailData.auditInfo" style="margin-top: 20px;">
          <h4>审核信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="审核人">{{ detailData.auditInfo.auditorName }}</el-descriptions-item>
            <el-descriptions-item label="审核时间">{{ detailData.auditInfo.auditTime }}</el-descriptions-item>
            <el-descriptions-item label="审核结果">
              <el-tag :type="detailData.auditInfo.auditResult === 1 ? 'success' : 'danger'">
                {{ detailData.auditInfo.auditResultDesc }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="审核意见">{{ detailData.auditInfo.auditOpinion || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="审核退货单"
      width="600px"
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
      >
        <el-form-item label="退货单号">
          <span>{{ currentAuditData?.returnNo }}</span>
        </el-form-item>
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="0">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditOpinion">
          <el-input
            v-model="auditForm.auditOpinion"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAuditSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const auditDialogVisible = ref(false)
const detailData = ref(null)
const currentAuditData = ref(null)

// 搜索表单
const searchForm = reactive({
  returnNo: '',
  status: null
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 审核表单
const auditForm = reactive({
  auditResult: 1,
  auditOpinion: ''
})

// 审核表单验证规则
const auditRules = {
  auditResult: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  auditOpinion: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
}

// 表单引用
const auditFormRef = ref()

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await axios.get('/purchase-return-order/page', {
      params: {
        current: pagination.current,
        size: pagination.size,
        status: searchForm.status,
        returnNo: searchForm.returnNo
      }
    })
    
    if (response.data.success) {
      // 只显示已提交、审核通过、审核驳回的退货单
      tableData.value = response.data.data.records.filter(item => item.status !== 0)
      pagination.total = response.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    returnNo: '',
    status: null
  })
  pagination.current = 1
  fetchData()
}

// 查看详情
const handleView = async (row) => {
  try {
    const response = await axios.get(`/purchase-return-order/${row.id}`)
    if (response.data.success) {
      detailData.value = response.data.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 审核
const handleAudit = (row) => {
  currentAuditData.value = row
  Object.assign(auditForm, {
    auditResult: 1,
    auditOpinion: ''
  })
  auditDialogVisible.value = true
}

// 提交审核
const handleAuditSubmit = async () => {
  try {
    await auditFormRef.value.validate()
    
    const response = await axios.post(`/purchase-return-order-audit/audit/${currentAuditData.value.id}`, null, {
      params: {
        auditorId: getCurrentUserId(), // 需要实现获取当前用户ID的方法
        auditOpinion: auditForm.auditOpinion,
        auditResult: auditForm.auditResult
      }
    })
    
    if (response.data.success) {
      ElMessage.success('审核成功')
      auditDialogVisible.value = false
      fetchData()
    }
  } catch (error) {
    console.error('审核失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchData()
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    1: 'warning', // 已提交
    2: 'success', // 审核通过
    3: 'danger'   // 审核驳回
  }
  return types[status] || 'info'
}

// 获取当前用户ID（需要根据实际认证框架实现）
const getCurrentUserId = () => {
  // TODO: 实现获取当前用户ID的逻辑
  return 1L
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.purchase-return-order-audit {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}
</style> 